package icu.lookyousmileface.config;

import icu.lookyousmileface.pojo.User;
import icu.lookyousmileface.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author starrysky
 * @title: UserRealm
 * @projectName spring-shiro-parent
 * @description:
 * @date 2021/2/1021:22
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权=》》》》》doGetAuthorizationInfo");

//        授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        获取当前的用户这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象
        User principal = (User) subject.getPrincipal();
        simpleAuthorizationInfo.addStringPermission(principal.getPerms());

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证=》》》》》doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){
            return null;//跑出异常UnknowAccoutException
        }
//        将认证了的用户放入session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
//        MD5,MD5颜值加密：MD5+username
//        密码认证由shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
